package com.yn.test;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;

import java.io.PrintStream;

class MainMethodAdapter extends AdviceAdapter {

    /**
     * Constructs a new {@link AdviceAdapter}.
     *
     * @param mv     the method visitor to which this adapter delegates calls.
     * @param access the method's access flags (see {@link Opcodes}).
     * @param name   the method's name.
     * @param desc   the method's descriptor (see {@link Type Type}).
     */
    protected MainMethodAdapter(MethodVisitor mv, int access, String name, String desc) {
        super(Opcodes.ASM6, mv, access, name, desc);
    }

    @Override
    protected void onMethodEnter() {
        super.onMethodEnter();
        sop("AdviceAdater: asm insert code");
    }

    @Override
    protected void onMethodExit(int opcode) {
        super.onMethodExit(opcode);
        sop("AdviceAdater: asm insert code");
    }

    private void sop(String msg) {
        mv.visitFieldInsn(Opcodes.GETSTATIC,
                Type.getInternalName(System.class), //"java/lang/System"
                "out",
                Type.getDescriptor(PrintStream.class) //"Ljava/io/PrintStream;"
        );
        mv.visitLdcInsn(msg);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                Type.getInternalName(PrintStream.class),
                "println",
                "(Ljava/lang/String;)V",
                false);
    }
}
